﻿using System.Collections.Generic;
using UnityEngine;

public class ClimberChecker : UnitTerrainCheckerBase
{
    /// <summary>
    /// 是否接触攀爬物
    /// </summary>
    public bool isClimber { get; set; }

    /// <summary>
    /// 当前接触攀爬物
    /// </summary>
    public ClimberInfo currentClimberInfo { get; set; }

    /// <summary>
    /// 碰撞箱
    /// </summary>
    private List<BoxCollider2D> colliBoxs
    {
        get
        {
            if (m_ColliBoxs == null)
            {
                m_ColliBoxs = new List<BoxCollider2D>();
                var collis = GetComponents<BoxCollider2D>();
                for (int i = 0; i < collis.Length; i++)
                {
                    collis[i].isTrigger = true;
                    m_ColliBoxs.Add(collis[i]);
                }
                m_ColliBoxs.Sort(ColliSortRule);
            }
            return m_ColliBoxs;
        }
    }
    private List<BoxCollider2D> m_ColliBoxs;

    /// <summary>
    /// 绳索底部
    /// </summary>
    public bool isClimberBottom => !m_IsClimberArray[0];

    /// <summary>
    /// 可以向上移动
    /// </summary>
    public bool isClimberTop => !m_IsClimberArray[1];


    private Collider2D[] m_Collis;
    private List<ClimberInfo> m_TempClimberInfos = new List<ClimberInfo>();
    private List<ClimberInfo> m_ClimberInfos = new List<ClimberInfo>();
    private bool[] m_IsClimberArray = new bool[2];

    protected override void UpdateTerrainInfo(long _)
    {
        m_ClimberInfos.Clear();
        for (int i = 0; i < colliBoxs.Count; i++)
        {
            var colliBox = colliBoxs[i];
            m_Collis = Physics2D.OverlapBoxAll((Vector2)transform.position + colliBox.offset, colliBox.size, 0f, layers);
            m_TempClimberInfos.Clear();
            foreach (var colli in m_Collis)
            {
                var climberInfo = colli.GetComponent<ClimberInfo>();
                if (climberInfo == null) continue;
                m_TempClimberInfos.Add(climberInfo);
            }
            m_IsClimberArray[i] = m_TempClimberInfos.Count > 0;
            if (m_IsClimberArray[i])
            {
                m_ClimberInfos.Add(m_TempClimberInfos[0]);
            }
        }
        isClimber = m_ClimberInfos.Count > 0;
        // 更新当前地形
        if (isClimber)
        {
            currentClimberInfo = m_ClimberInfos[0];
        }
        else
        {
            currentClimberInfo = null;
        }
    }

    private int ColliSortRule(BoxCollider2D x, BoxCollider2D y)
    {
        return x.offset.y.CompareTo(y.offset.y);
    }
}